package la.iok.aone.monitor.youtube.startup;

import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import java.util.List;

@Component
public class DirectoryMonitor implements ApplicationRunner {
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 扫描间隔（单位：秒）
     * 默认值：5
     */
    @Value("${config.import.scan.interval:5}")
    private int scanInterval;
    /**
     * 扫描导入目录
     * 默认值：/tmp/monitor/youtube
     */
    @Value("${config.import.scan.dir:/tmp/monitor/youtube}")
    private String scanImportDir;
    /**
     * 扫描导入的文件扩展名
     * 默认值：.xls
     */
    @Value("${config.import.scan.file.extension:.xls}")
    private String scanImportFileExtensions;
    @Autowired
    private FileAlterationListener importFileAlterationListener;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<String> extensions = Arrays.asList(scanImportFileExtensions.split(","));
        if (null != scanImportDir && !extensions.isEmpty()) {
            monitorImport(scanImportDir, extensions);
        }
    }

    /**
     * 监控节目导入目录
     */
    private void monitorImport(String scanImportDir, final List<String> extensions) {
        //文件变更器
        FileAlterationMonitor monitor = new FileAlterationMonitor(scanInterval * 1000);//5s扫描一次

        //目录观察者 观察节目导入目录 只观察xml
        FileAlterationObserver importObserver = new FileAlterationObserver(new File(scanImportDir), new FileFilter() {
            public boolean accept(File pathname) {
                if (pathname.isDirectory()
                        && !pathname.isHidden() // 排除隐藏文件
                        && !"$RECYCLE.BIN".equalsIgnoreCase(pathname.getName()) // 排除ntfs文件系统隐藏文件夹
                        && !"System Volume Information".equalsIgnoreCase(pathname.getName())) {
                    return true;
                } else if (-1 != pathname.getName().lastIndexOf(".")
                        && extensions.contains(pathname.getName().substring(
                        pathname.getName().lastIndexOf(".")).toLowerCase())
                        // 排除隐藏文件
                        && !pathname.isHidden()) {
                    return true;
                }
                return false;
            }
        });
        importObserver.addListener(importFileAlterationListener);
        monitor.addObserver(importObserver);

        // 启动目录监控
        try {
            for (FileAlterationObserver observer : monitor.getObservers()) {
                logger.info("Startup directory[{}] monitor ...", observer.getDirectory().getPath());
            }
            monitor.start();
        } catch (Exception e) {
            logger.error("", e);
        }
    }
}
